package com.edfu.core.contentmgt.jcr.util;

import java.util.ArrayList;
import java.util.List;

import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.PropertyIterator;
import javax.jcr.RepositoryException;
import javax.jcr.version.Version;

import org.apache.jackrabbit.JcrConstants;

import com.edfu.core.contentmgt.jcr.vo.Content;
import com.edfu.core.contentmgt.jcr.vo.ContentProperty;


public class ContentMgtUtil {
	
	public static boolean isNullOrEmpty(String input) {
		if (input == null || input.trim().length() == 0)
			return true;
		else
			return false;
	}
	
	public static Content convertJCRNodeToEduContent(Node node) throws RepositoryException {
		Content content = new Content();
		content.setContentUUID(node.getIdentifier()) ;
		content.setFullyQualifiedContentName(node.getPath());
		content.setVersionable(node.isNodeType(JcrConstants.MIX_VERSIONABLE));
		List<ContentProperty> contentProperties = new ArrayList<ContentProperty>();
		PropertyIterator it = node.getProperties() ;
		while(it.hasNext()) {
			Property property = it.nextProperty() ;
			if (property.getName().startsWith("jcr:"))
				continue;
			ContentProperty contentProperty = new ContentProperty();
			contentProperty.setPropertyName(property.getName());
			contentProperty.setPropertyValue(property.getValue().getString()) ;
			contentProperties.add(contentProperty);
		}
		content.setProperties(contentProperties);
		return content;
	}
	
	public static com.edfu.core.contentmgt.jcr.vo.Version convertJCRVersionToEduVersion(Version version, String baseFileAbsPath ) throws RepositoryException {
		com.edfu.core.contentmgt.jcr.vo.Version eduVersion = new com.edfu.core.contentmgt.jcr.vo.Version();
		eduVersion.setContentUUID(version.getIdentifier());
		eduVersion.setFullyQualifiedContentName(version.getPath());
		eduVersion.setParentContentFullyQualifiedName(baseFileAbsPath);
		eduVersion.setParentContentUUID(version.getFrozenNode().getIdentifier());
		eduVersion.setVersionNumber(version.getName());
		List<ContentProperty> contentProperties = new ArrayList<ContentProperty>();
		PropertyIterator it = version.getProperties() ;
		while(it.hasNext()) {
			Property property = it.nextProperty() ;
			if (property.getName().startsWith("jcr:"))
				continue;
			ContentProperty contentProperty = new ContentProperty();
			contentProperty.setPropertyName(property.getName());
			contentProperty.setPropertyValue(property.getValue().getString()) ;
			contentProperties.add(contentProperty);
		}
		eduVersion.setProperties(contentProperties);
		return eduVersion;
	}
	
}
